<template>
  <n-card title="商品属性">
    <template #header-extra>
      <n-popover trigger="click">
        <template #trigger>
          <n-button size="small" type="primary">新增属性</n-button>
        </template>
        <n-space align="center">
          <n-input v-model:value="addAttrName" placeholder="请输入属性名称" />
          <n-button type="primary" text @click="handleAddAttr">确定</n-button>
        </n-space>
      </n-popover>
    </template>
    <n-grid :cols="2" :x-gap="24">
      <n-form-item-gi v-for="attr in prodAttrList" :label="attr.attrNm" :key="attr.attrCd">
        <n-flex align="center" :wrap="false" style="flex: 1">
          <n-input
            v-if="[DataTpEnum.TEXT].includes(attr.dataTpCd)"
            :placeholder="'请输入' + attr.attrNm"
            v-model:value="attr.val"
            :maxlength="attr.len"
            show-count
            @update:value="handleUpdateAttrList"
          />
          <n-input-number
            v-if="[DataTpEnum.NUMBER].includes(attr.dataTpCd)"
            :placeholder="'请输入' + attr.attrNm"
            v-model:value="attr.numVal"
            :min="attr.min"
            :max="attr.max"
            :precision="attr.prec"
            :step="attr.step"
            style="width: 100%"
            @update:value="handleUpdateAttrList"
          >
            <template v-if="attr.unitNm" #suffix>{{ attr.unitNm }}</template>
          </n-input-number>
          <n-date-picker
            v-if="[DataTpEnum.DATE].includes(attr.dataTpCd)"
            style="width: 100%"
            :placeholder="'请输入' + attr.attrNm"
            v-model:formatted-value="attr.dateVal"
            :format="attr.frmt || 'yyyy-MM-dd'"
            type="date"
            @update:formatted-value="handleUpdateAttrList"
          />
          <n-select
            v-if="[DataTpEnum.ENUM].includes(attr.dataTpCd)"
            :placeholder="'请输入' + attr.attrNm"
            v-model:value="attr.valList"
            :options="attr.optList"
            label-field="optLab"
            value-field="optVal"
            :multiple="attr.multFlg === 1"
            @update:value="handleUpdateAttrList"
          />
          <!-- 删除属性 -->
          <n-popconfirm @positive-click="handleDelSkuAttr(attr)">
            <template #trigger>
              <n-button type="error" text>
                <template #icon>
                  <n-icon>
                    <DeleteOutlined />
                  </n-icon>
                </template>
              </n-button>
            </template>
            确认删除“{{ attr.attrNm }}”？
          </n-popconfirm>
        </n-flex>
      </n-form-item-gi>
    </n-grid>
  </n-card>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import { DeleteOutlined } from '@vicons/antd';
import { DataTpEnum } from '@/modules/bmppd/enums/DataTpEnum';
import { ProdTpAttr } from './attrDataClass';

defineOptions({
  name: 'ProdAttrCard'
});

class ProdAttrItem extends ProdTpAttr {
  valList: string[] = []; //枚举多选值储存
  numVal: number | null = null; //数字值存储
  dateVal: string | null = null; //日期值存储
}

const props = withDefaults(
  defineProps<{
    attrList: ProdTpAttr[];
    createAttrCd: () => string;
  }>(),
  {
    attrList: () => []
  }
);
const emits = defineEmits<{
  (e: 'update:attrList', list: ProdTpAttr[]): void;
}>();

const prodAttrList = ref<ProdAttrItem[]>([]);
const addAttrName = ref<string>('');

watch(
  () => props.attrList,
  (attrList) => {
    prodAttrList.value = attrList.map((item) => {
      let valList: string[] = [];
      if (item.dataTpCd === DataTpEnum.ENUM && item.multFlg === 1) {
        valList = item.val ? item.val.split(',') : [];
      }
      let numVal: number | null = null;
      if (item.dataTpCd === DataTpEnum.NUMBER) {
        numVal = isNumeric(item.val) ? Number(item.val) : null;
      }
      let dateVal: string | null = null;
      if (item.dataTpCd === DataTpEnum.DATE) {
        dateVal = item.val || null;
      }
      return { ...item, numVal, dateVal, valList };
    });
  },
  { deep: true }
);

function handleUpdateAttrList() {
  const list: ProdTpAttr[] = [];
  prodAttrList.value.forEach((attr) => {
    if (attr.dataTpCd === DataTpEnum.ENUM && attr.multFlg === 1) {
      attr.val = attr.valList.join(',');
    } else if (attr.dataTpCd === DataTpEnum.NUMBER) {
      attr.val = isNumeric(attr.numVal) ? String(attr.numVal) : '';
    } else if (attr.dataTpCd === DataTpEnum.DATE) {
      attr.val = attr.dateVal ?? '';
    }
    list.push(attr);
  });
  emits('update:attrList', list);
}

//新增属性
function handleAddAttr() {
  const attrNmArr = prodAttrList.value.map((item) => item.attrNm);
  if (attrNmArr.includes(addAttrName.value)) {
    window.$message.error('属性名称重复');
    return;
  }
  const newAttr = new ProdAttrItem();
  newAttr.attrCd = props.createAttrCd();
  newAttr.attrNm = addAttrName.value;
  prodAttrList.value.push(newAttr);
  addAttrName.value = '';
  handleUpdateAttrList();
}

//删除属性
function handleDelSkuAttr(attr: ProdAttrItem) {
  const index = prodAttrList.value.findIndex((item) => attr.attrCd === item.attrCd);
  if (index > -1) {
    prodAttrList.value.splice(index, 1);
  }
  handleUpdateAttrList();
}

function isNumeric(value: string | number | null | undefined): boolean {
  if (value === undefined || value === null) return false;
  if (typeof value === 'string' && !value) return false;
  return !Number.isNaN(Number(value));
}
</script>

<style lang="scss" scoped></style>
